<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="84px">
      <el-form-item label="设备编码" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入设备编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="厂商型号" prop="model">
        <el-input
          v-model="queryParams.model"
          placeholder="请输入厂商型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌名称" prop="brandName">
        <el-input
          v-model="queryParams.brandName"
          placeholder="请输入品牌名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="包含了模块" prop="moduleCode">
        <el-select
          size="small"
          v-model="queryParams.moduleCode"
          placeholder="请选择模块"
          clearable
          filterable
          class="custom-input-width"
        >
          <el-option
            v-for="item in deviceModules"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:info:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:info:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:info:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['device:info:import']"
        >导入
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['device:info:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="设备编码" align="center" prop="code" width="190"/>
      <el-table-column label="厂商型号" align="center" prop="model"/>
      <el-table-column label="设备名称" align="center" prop="name"/>
      <el-table-column label="BOM编码" align="center" prop="bomCode"/>
      <el-table-column label="设备规格" align="center" prop="spec"/>
      <el-table-column label="品牌名称" align="center" prop="brandName"/>
      <el-table-column label="描述" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['device:info:query']"
          >详细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:info:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:info:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 详细对话框 -->
    <el-dialog title="详细" :visible.sync="openView" custom-class="custom-dialog" width="1000px" append-to-body>
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本资料" name="baseInfo">
          <baseInfo :baseinfo="selection"/>
        </el-tab-pane>
        <el-tab-pane label="模块信息" name="moduleInfo">
          <moduleInfo :modules="selection.modules"/>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>

    <!-- 添加或修改设备对话框 -->
    <el-dialog v-dialogDrag :close-on-click-modal=false :title="title" :visible.sync="open" @close="closeE"
               width="1400px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="设备编码" prop="code" v-if="form.id">
              <el-input v-model="form.code" disabled/>
            </el-form-item>
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入设备名称"/>
            </el-form-item>
            <el-form-item label="厂商型号" prop="model">
              <el-input v-model="form.model"/>
            </el-form-item>
            <el-form-item label="设备规格" prop="spec">
              <el-input
                v-model="form.spec"
                placeholder="请输入设备规格"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="BOM编码" prop="bomCode">
              <el-input v-model="form.bomCode" placeholder="请输入BOM编码"/>
            </el-form-item>
            <el-form-item label="品牌" prop="brand">
              <el-select
                v-model="form.brand"
                value-key="code"
                placeholder="品牌"
                clearable
                class="custom-input-width"
                filterable
                @change="changeSelect($event)"
              >
                <div v-for="bra in deBrands" :key="bra.code">
                  <el-tooltip effect="dark" content="已停用" placement="top-start">
                    <el-option
                      disabled
                      :key="bra.code"
                      :label="bra.name"
                      :value="bra"
                    />
                  </el-tooltip>
                </div>
                <el-option
                  v-for="mau in brands"
                  :key="mau.code"
                  :label="mau.name"
                  :value="mau"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="描述" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-col>

          <el-col :span="16">
            <el-form-item label="" prop="model">
              <div style="margin-left: -80px">
                <div class="transfer-title">请选择设备模块</div>
                <el-transfer
                  filterable
                  filter-placeholder="请输入模块名称"
                  v-model="selectedModelCodeList"
                  :props="{
                  key: 'code',
                  label: 'name'
                  }"
                  :data="deviceModules"
                  :titles="['可选择模块','已选择模块']"
                  @change="handleTransferChange"
                >
                  <template slot-scope="{ option }">
                    <el-tooltip placement="top" effect="light" :disabled="disabledTooltip(option)">
                      <div slot="content">
                        {{ option.name }}-{{ option.model }}
                      </div>
                      <span>{{ option.name }}-{{ option.model }}</span>
                    </el-tooltip>
                  </template>
                </el-transfer>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  删除模块失败提示-->
    <el-dialog
      :visible.sync="deleteFailedDialogVisible"
      top="100px !important"
      width="800px"
      :close-on-click-modal="false"
      z-index="1002"
    >
      <template slot="title">
        提示：<span class="tip" style="color: red">设备正在被部署中，若要删除，请先从设备部署管理界面解绑对应的设备！</span>
      </template>
      <el-table :data="deviceInUsedList" max-height="600px">
        <el-table-column property="deviceId" label="设备ID" align="center" width="190"/>
        <el-table-column property="deviceName" label="设备部署名称" align="center"/>
        <el-table-column property="deleteDeviceCode" label="引用设备编码" align="center" width="190"/>
        <el-table-column property="deleteDeviceName" label="引用设备名称" align="center"/>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="small" type="primary" @click="navToPlaceManagerUnbind(scope.row)">去解绑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteFailedDialogVisible = false">确 定</el-button>
      </div>
    </el-dialog>

    <import-file-dialog
      v-model="uploadDialogVisible"
      templateFileName="设备信息导入模板"
      uploadApi="/device/info/import"
      templateDownloadUrl="/device/info/export"
      @onSuccess="handleUploadFileSuccess"
    />
  </div>
</template>

<script>
import {listInfo, getInfo, delInfo, addInfo, updateInfo} from "@/api/device/info";
import baseInfo from "./baseInfo";
import moduleInfo from "./moduleInfo";
import draggable from 'vuedraggable'

export default {
  name: "DeviceInfo",
  dicts: ['sys_normal_disable'],
  components: {baseInfo, moduleInfo, draggable},
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示详情弹出层
      openView: false,
      //选中的数据（单条数据）
      selection: {},
      //停用的品牌
      deBrands: [],
      activeTab: "baseInfo",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        code: undefined,
        model: undefined,
        name: undefined,
        brandName: undefined,
        status: 0,
        moduleCode: undefined
      },
      // 表单参数
      form: {},
      // 表单校验`
      rules: {
        bomCode: [
          {required: true, message: "BOM编码不能为空", trigger: "blur"}
        ],
        model: [
          {required: true, message: "厂商型号不能为空", trigger: "blur"}
        ],
        spec: [
          {required: true, message: "设备规格不能为空", trigger: "blur"}
        ],
        name: [
          {required: true, message: "设备名称不能为空", trigger: "blur"}
        ],
        brand: [
          {required: true, message: "品牌不能为空", trigger: "change"}
        ],
      },
      // 打开弹窗当前默认选中的模块code数组
      selectedModelCodeList: [],
      // 设备被引用中弹窗
      deleteFailedDialogVisible: false,
      // 设备删除时被设备引用列表
      deviceInUsedList: [],
      uploadDialogVisible: false
    };
  },
  computed: {
    //有效的品牌，用于下拉列表
    brands: {
      get() {
        return this.$store.state.device.brands
      },
    },
    //设备模块
    deviceModules() {
      return this.$store.state.device.deviceModules || []
    },
  },
  created() {
    // 加载设备模块保存到vuex
    this.$store.dispatch('LoadDeviceModules');
  },
  methods: {
    // 上传成功
    handleUploadFileSuccess(res) {
      if (res.data === "上传成功！") this.getList()
    },
    handleImport() {
      this.uploadDialogVisible = true
    },
    // 跳转到设备部署页面解绑
    navToPlaceManagerUnbind(row) {
      this.deleteFailedDialogVisible = false;
      this.$router.push({
        name: 'PlaceManager',
        query: {deviceCode: row.deviceCode}
      })
    },
    // 判断文字长度超过20启用tooltip
    disabledTooltip(option) {
      const length = option.name.length + option.model.length;
      return length < 20
    },
    // 选中模块改变时触发
    handleTransferChange(selectedCodeList) {
      // 找到选中模块的信息
      const selectModelList = this.deviceModules.filter(item => {
        return selectedCodeList.includes(item.code)
      })
      this.form.modules = selectModelList;
    },

    /**品牌下拉列表更改 */
    changeSelect(selection) {
      this.form.brandCode = selection.code;
      this.form.brandName = selection.name;
    },

    //对话框关闭是的回调函数
    closeE() {
      this.deBrands = [];
    },

    /** 查询设备列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then(response => {
        // 是否已经加载过设备列表标记改为true
        if (!this.alreadyGetList) this.alreadyGetList = true;
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      // 清空选中的模块ID
      this.selectedModelCodeList = [];
      this.form = {
        id: null,
        code: null,
        model: null,
        name: null,
        bomCode: null,
        brandCode: null,
        brandName: null,
        modules: [],
        spec: null,
        brand: null,
        status: 0,//新增窗口打开时状态默认正常
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        code: undefined,
        model: undefined,
        name: undefined,
        brandName: undefined,
        status: 0,
        moduleCode: undefined
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备";
    },
    /**详情按钮操作 */
    handleView(row) {
      this.selection = row;
      this.openView = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // console.log('修改按钮操作',row);
      const id = row.id || this.ids;
      getInfo(id).then(response => {
        this.brands.forEach(element => {
          if (element.code === row.brandCode) {
            response.data.brand = element;
          }
          const modules = response.data.modules || [];

          // 打开弹窗时默认选中之前已存在的的模块
          this.selectedModelCodeList = modules.map(item => {
            return item.code
          })
        })

        //如果当前选中的模块所属的品牌已经停用，则显示模块表的品牌code和品牌名称
        if (response.data.brand === undefined) {
          response.data.brand = {code: response.data.brandCode, name: response.data.brandName};
          this.deBrands.push({code: response.data.brandCode, name: response.data.brandName});
        }
        this.form = response.data;
        this.open = true;
        this.title = "修改设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              // 更新保存在vuex设备型号选项数据
              this.$store.dispatch('LoadDeviceTypeAndBomCodeOption');
            });
          } else {
            addInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              // 更新保存在vuex设备型号选项数据
              this.$store.dispatch('LoadDeviceTypeAndBomCodeOption');
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$store.state.message.delConfirm).then(function () {
        return delInfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 更新保存在vuex设备型号选项数据
        this.$store.dispatch('LoadDeviceTypeAndBomCodeOption');
      }).catch((res) => {
        this.loading = false;
        const list = res.data;
        if (list.length) {
          this.deviceInUsedList = list;
          this.deleteFailedDialogVisible = true;
        }
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());

      this.download('device/info/export', {
        ...this.queryParams,
        exportBlank: '0'
      }, `设备管理_${currentDate}.xlsx`)
    }
  },
  beforeRouteEnter(to, from, next) {
    const {deviceCode, moduleCode, brandName} = to.query;
    // 如果存在跳转参数deviceCode,自动填入查询条件
    if (deviceCode || moduleCode || brandName) {
      next(vm => {
        vm.resetForm("queryForm");
        vm.queryParams.code = deviceCode;
        vm.queryParams.moduleCode = moduleCode;
        vm.queryParams.brandName = brandName;
        vm.getList();
      })
    } else {
      // 不存在查询参数
      next(vm => {
        // 判断是否已经加载过列表了，当还没有加载过列表时才调用获取列表接口
        if (!vm.alreadyGetList) {
          vm.getList();
        }
      });
    }
  },
  /*  在离开页面时清空跳转携带的参数 暂时不用
    beforeRouteLeave(to,from,next){
      const {deviceCode,moduleCode,brandName} = this.$route.query;
      // 如果当前路由存在跳转参数，跳转前清空参数
      if(deviceCode || moduleCode || brandName){
        this.resetForm("queryForm");
        // 重新加载列表
        this.getList();
      }
      next();
    },*/
};
</script>
<style lang="scss" scoped>
.custom-input-width {
  width: 100%;
}

.transfer-title {
  margin-bottom: 10px;
  font-size: 14px;
  font-weight: bold;
  line-height: 36px;
  vertical-align: middle;
}

::v-deep .el-transfer-panel {
  width: 350px;
}

::v-deep .el-transfer-panel__body {
  height: 402px;
}

::v-deep .el-transfer-panel__list {
  height: 350px;
}
</style>
